import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterstudyapplast/business/viewmodels/user_viewmodel.dart';
import 'package:flutterstudyapplast/common/event/events.dart';
import 'package:flutterstudyapplast/manager/app_manager.dart';
import 'package:flutterstudyapplast/services/service_locator.dart';
import 'package:flutterstudyapplast/ui/page/page_register.dart';
import 'package:toast/toast.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  FocusNode pwdNode = FocusNode();
  var formKey = GlobalKey<FormState>();
  String _username;
  String _pwd;
  bool _isObscure = true;
  Color _pwdIconColor;
  UserViewModel _userViewModel = serviceLocator<UserViewModel>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    pwdNode.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("登录",style: TextStyle(color: Colors.white,fontSize: 18),),),
      body: Form(
        key: formKey,
        child: ListView(
          padding: EdgeInsets.all(20),
          children: <Widget>[
            _buildUsername(),
            _buildPwd(),
            _buildLogin(),
            _buildRegister()
          ],
        ),
      )
    );
  }
  Widget _buildUsername(){
    return TextFormField(
      autofocus: true,
      textInputAction: TextInputAction.next,
      initialValue: _username,
      decoration: InputDecoration(labelText: "用户名"),
      onEditingComplete: (){
        FocusScope.of(context).requestFocus(pwdNode);
      },
      validator: (value){
        if(value == null || value.trim().isEmpty){
          return "请输入用户名";
        }
        _username = value;
      },
    );
  }
  Widget _buildPwd(){
    return TextFormField(
      focusNode: pwdNode,
      obscureText: _isObscure,
      textInputAction: TextInputAction.done,
      initialValue: _pwd,
      decoration: InputDecoration(
        labelText: "密码",
        suffixIcon: IconButton(
          icon: Icon(Icons.remove_red_eye,color: _pwdIconColor,),
          onPressed: (){
            setState(() {
              _isObscure = !_isObscure;
              ///密码隐藏 图标颜色控制
              _pwdIconColor = _isObscure
                  ? Colors.grey
                  : Theme.of(context).iconTheme.color;
            });
          },
        )
      ),
      onEditingComplete: _doLogin,
      validator: (value){
        if(value == null || value.trim().isEmpty){
          return "请输入用户名";
        }
        _pwd = value;
      },
    );
  }
  Widget _buildLogin(){
    return Container(
      height: 45,
      color: Theme.of(context).primaryColor,
      child: RaisedButton(child:Text("登录",style: TextStyle(fontSize: 18,color: Colors.white),),onPressed: _doLogin),
      margin: EdgeInsets.only(top:18,bottom: 18),
    );
  }
  Widget _buildRegister(){
    return Padding(
      padding: EdgeInsets.only(top: 10),
      child: Row(
        children: <Widget>[
          Text("没有账号？",style: TextStyle(color: Colors.black),),
          GestureDetector(
            child: Text("点击注册",style: TextStyle(color: Colors.blue),),
            onTap: () async {
              ///去往注册页
              Navigator.push(context, MaterialPageRoute(builder: (context){
                return RegisterPage();
              }));
            },
          )
        ],
      ),
    );
  }
  void _doLogin() async{
    pwdNode.unfocus();
    if(formKey.currentState.validate()){
      showDialog(context: context,barrierDismissible: false,builder: (context){
        return Center(child: CircularProgressIndicator(),);
      });
      var result = await _userViewModel.login(_username, _pwd);
      Navigator.pop(context);///取消对话框
      if(!result){
        Toast.show("登录失败", context,duration: Toast.LENGTH_SHORT,gravity: Toast.CENTER);
      }else{
        //AppManager.prefs.setString(key, value)
        AppManager.eventBus.fire(LoginEvent(_username));
        Navigator.pop(context);
      }
    }
  }
}
